package com.hanter.android.saf;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.OutputStream;

/**
 * 文件名：Utils <br/>
 * 描述：Uri工具类
 * 创建时间：2022/03/21 15:47
 *
 * @author wangmingshuo
 */
class Utils {

    @Nullable
    public static String getPath(@NonNull Context context, @NonNull Uri uri) {
        try (Cursor cursor = context.getContentResolver().query(uri,
                new String[]{
                        MediaStore.MediaColumns.DATA
                },
                null,
                null,
                null)) {
            if (cursor != null && cursor.moveToFirst()) {
                return cursor.getString(0);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static boolean exists(@NonNull Context context, @NonNull Uri uri) {
        String scheme = uri.getScheme();
        if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            if (DocumentsContract.isDocumentUri(context, uri)) {
                return resolveUri(context, uri, DocumentsContract.Document.COLUMN_DOCUMENT_ID);
            } else {
                return resolveUri(context, uri, BaseColumns._ID) && testOpenable(context, uri);
            }
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            return uri.getPath() != null && new File(uri.getPath()).exists();
        } else {
            return false;
        }
    }

    private static boolean resolveUri(@NonNull Context context, Uri uri, String column) {
        try (Cursor cursor = context.getContentResolver().query(uri, new String[]{column},
                null, null, null, null)) {
            return cursor != null && cursor.moveToFirst();
        }
    }

    private static boolean testOpenable(@NonNull Context context, @NonNull Uri uri) {
        try (OutputStream os = context.getContentResolver().openOutputStream(uri, "rw")) {
            return os != null;
        } catch (FileNotFoundException e) {
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
